package net.dwade.dubbo.adapter.internal;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.dwade.dubbo.adapter.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class EsbParamConvertHandler implements ServiceRequestResponseProcessor {

	private static Logger logger = LoggerFactory.getLogger( EsbParamConvertHandler.class );
	
	@Override
	public Object[] resolveProviderArguments(Method target, String requestString) {
		
		Class<?>[] argumentTypes = target.getParameterTypes();
		Object[] objs = new Object[argumentTypes.length];
		
		JSONObject jsonObjct = JSON.parseObject( requestString );
		JSONArray outDataJsons = JSONArray.parseArray(requestString);
		
		for (int i = 0; i < argumentTypes.length; i++) {
			JSONObject obj = outDataJsons.getJSONObject(i);
			obj.toJavaObject( argumentTypes[i] );
		}
		
		return objs;
	}

	@Override
	public String handleProviderReturnValue(Method method, Object returnValue) {
		return JsonUtils.toJson(returnValue);
	}

	@Override
	public String handleConsumerArguments(Method method, Object[] arguments) {
		return JSONArray.toJSONString(arguments);
	}

	@Override
	public Object resolveConsumerReturnValue(Method method, String stringResponse) {
		
		JSONObject jsonObjct = JSON.parseObject( stringResponse );
		String outDataJson = JsonUtils.getNestedValue(jsonObjct, "ROOT.OUT_DATA");
		
		//对于异常信息直接抛出由调用者进行处理
		if (StringUtils.isEmpty(outDataJson)) {
			String esbRetCode = JsonUtils.getNestedValue(jsonObjct, "ROOT.ESBRETCODE");
			String retMsg = JsonUtils.getNestedValue(jsonObjct, "ROOT.RETURN_MSG");
			logger.error("调用ESB发生异常，异常码：{}，异常信息：{}", esbRetCode, retMsg);
			throw new RuntimeException(retMsg);
		}
		Class<?> returnType = method.getReturnType();
		//泛型处理
		Type type = method.getGenericReturnType();
		Object object = null;
		// 判断获取的类型是否是参数化类型
		if (type instanceof ParameterizedType) { 
			object = JSON.parseObject( outDataJson, type );
        } else {
        	object = JSON.parseObject( outDataJson, returnType );
        }
		return object;
		
	}

}
